package cn.autumnorange.app.snowflake.consumer.controller;

import cn.autumnorange.app.common.dto.ResultDto;
import cn.autumnorange.app.snowflake.api.SnowFlakeService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

@Slf4j
@RestController
public class SnowFlakeController implements SnowFlakeService {
  @Autowired SnowFlakeService snowFlakeService;

  @Override
  public ResponseEntity<ResultDto<Long>> getGlobalId() {
    ResponseEntity<ResultDto<Long>> resultDto = snowFlakeService.getGlobalId();
    System.out.println(
        "SnowFlakeController in---------------------" + resultDto.getBody().getData());
    return resultDto;
  }

  public ResponseEntity<ResultDto> test(HttpServletRequest request) {
    System.out.println("----------------SnowFlakeControllerTest----------------");

    Authentication authorization = SecurityContextHolder.getContext().getAuthentication();
    if (authorization != null) {
      Object obj = authorization.getPrincipal();
      if (obj instanceof UserDetails) {
        UserDetails userDetails = (UserDetails) authorization.getPrincipal();
        log.info(userDetails.toString());
      }
    }
    Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
      String key = (String) headerNames.nextElement();
      System.out.println(key + ": " + request.getHeader(key));
    }
    ResultDto resultDto = new ResultDto();
    String authenticationStr=JSONObject.toJSONString(authorization.getDetails());
    resultDto.setMessage(authenticationStr);
    return ResponseEntity.ok(resultDto);
  }
}
